#!/usr/bin/env bash


help(){
    cat<<__EOF__
Usage:  m flightmode [OPTIONS]

Description:  Turn flightmode on or off, this will affect both Wi-Fi and Bluetooth.

Options:
  --help      Show this help message
  --enable    Enable flightmode
  --disable   Disable flightmode
__EOF__
}

# default wifi device
_WIFI_DEVICE=${_WIFI_DEVICE:-en0}

toggle_flightmode(){
    local mode
    local int_mode
    case "${1}" in
        off)
            # this is not wrong, it is just the opposite
            mode="on"
            int_mode=1
            ;;
        on)
            # this is not wrong, it is just the opposite
            mode="off"
            int_mode=0
            ;;
        *)
            echo "Invalid mode: ${1}"
            return 1
            ;;
    esac
    networksetup -setairportpower ${_WIFI_DEVICE} ${mode}
    sudo defaults write \
        /Library/Preferences/com.apple.Bluetooth ControllerPowerState -int ${int_mode} && \
        sudo killall -HUP blued
}

# Main script execution
case $1 in
    --help)
        help
        ;;
    --disable)
        toggle_flightmode off
        ;;
    --enable)
        toggle_flightmode on
        ;;
    *)
        help && exit 1
        ;;
esac
